class Solution
{
public:
    vector<int> lexicographicallySmallestArray(vector<int> &nums, int limit)
    {
        int n = nums.size();
        vector<pair<int, int>> numsWithIndex;
        for (int i = 0; i < nums.size(); i++)
        {
            numsWithIndex.push_back({nums[i], i});
        }
        sort(numsWithIndex.begin(), numsWithIndex.end());

        vector<vector<int>> groups{{numsWithIndex[0].first}};
        vector<int> numGroup(n);
        int groupId = 0;
        for (int i = 1; i < n; ++i)
        {
            if (numsWithIndex[i].first - numsWithIndex[i - 1].first > limit)
            {
                ++groupId;
                groups.push_back({numsWithIndex[i].first});
            }
            else
            {
                groups[groupId].push_back(numsWithIndex[i].first);
            }
            numGroup[numsWithIndex[i].second] = groupId;
        }
        vector<int> groupPos(groups.size(), 0);
        vector<int> ans(n);
        for (int i = 0; i < n; ++i)
        {
            int groupId = numGroup[i];
            ans[i] = groups[groupId][groupPos[groupId]];
            ++groupPos[groupId];
        }
        return ans;
    }
};